from datetime import datetime
import random
import re
from flask import json, jsonify
from flask import render_template
from flask import session
from info.models import User
from info.modules.passport import passport_blu
from flask import abort
from flask import current_app
from flask import make_response
from flask import request
# from info.libs.yuntongxun.sms import CCP
from info.utils.common import user_login
from info.utils.response_code import RET

from info import constants, db
from info import redis_store
from info.utils.captcha.captcha import captcha


@passport_blu.route('/')
@user_login
def index():

    return current_app.send_static_file("html/index.html")


@passport_blu.route("/login" ,methods=["POST","GET"] )
@user_login
def login():

    mobile = request.json.get("mobile")
    password = request.json.get("password")
    if not all([mobile, password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="数据库查询失败")
    if not user:
        return jsonify(errno=RET.NODATA, errmsg="用户还没有注册")
    if not user.check_passowrd(password):
        return jsonify(errno=RET.DATAERR, errmsg="密码输入错误")

    session["user_id"] = user.id
    return jsonify(errno=RET.OK, errmsg="登录成功")


@passport_blu.route('/imagecode', methods=["GET","POST"])
@user_login
def get_image_code():

    cur = request.args.get("cur", None)
    print(cur)
    if not cur:
        return abort(403)
    name,text,image = captcha.generate_captcha()
    current_app.logger.info("图片验证码内容是：%s" % text)
    try:
        redis_store.setex("ImageCodeId_" + cur, constants.IMAGE_CODE_REDIS_EXPIRES,text)
    except Exception as e:
        current_app.logger.error(e)
        abort(500)
    response = make_response(image)
    response.headers["Content-Type"] = "image/jpg"
    print(text)
    return response

@passport_blu.route('/smscode', methods=["GET","POST"])
@user_login
def send_sms_code():

    params_dict = request.json
    mobile = params_dict.get("mobile")
    image_code = params_dict.get("image_code")
    image_code_id = params_dict.get("image_code_id")
    if not all([mobile, image_code, image_code_id]):
        # {"errno": "4100", "errmsg": "参数有误"}
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
    if not re.match('1[35678]\\d{9}', mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号格式不正确")
    try:
        real_image_code = redis_store.get("ImageCodeId_" + image_code_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    if not real_image_code:
        return jsonify(errno=RET.NODATA, errmsg="图片验证码已过期")

    if real_image_code.upper() != image_code.upper():
        print(real_image_code.upper())
        print(image_code.upper())
        return jsonify(errno=RET.DATAERR, errmsg="验证码输入错误")
    sms_code_str = "%06d" % random.randint(0, 999999)
    current_app.logger.info("短信验证码内容是：%s" % sms_code_str)
    # result = CCP().send_template_sms(mobile, [sms_code_str,
    #                                           constants.SMS_CODE_REDIS_EXPIRES / 5],  "1")
    # if result != 0:
    #     return jsonify(errno=RET.THIRDERR, errmsg="发送短信失败")
    try:
        redis_store.setex("SMS_" + mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code_str)
    except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据保存失败")
    return jsonify(errno=RET.OK, errmsg="发送成功")


@passport_blu.route('/user', methods=["GET","POST"])
@user_login
def register():
    if request.method == 'GET':
        return current_app.send_static_file("html/register.html")

    param_dict = request.json
    mobile = param_dict.get("mobile")
    phonecode = param_dict.get("phonecode")
    password = param_dict.get("password")


    if not all([mobile, phonecode, password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数")
    if not re.match('1[35678]\\d{9}', mobile):
        return jsonify(errno=RET.PARAMERR, errmsg="手机号格式不正确")
    try:
        real_sms_code = redis_store.get("SMS_" + mobile)
    except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据查询失败")

    if not real_sms_code:
        return jsonify(errno=RET.NODATA, errmsg="验证码已过期")
    if real_sms_code != phonecode:
        return jsonify(errno=RET.DATAERR, errmsg="验证码输入错误")
    user = User()
    user.name = mobile
    user.mobile = mobile
    user.password = password

    user.last_login = datetime.now()
    try:
        db.session.add(user)

        db.session.commit()

    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")

    session["user_id"] = user.id

    return jsonify(errno=RET.OK, errmsg="注册成功")
